﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Model;
using System.ComponentModel;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Model.ParamModel;
using System.Text;
using System.Text.RegularExpressions;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class SupplierController : BaseController
    {
        [Description("供应商列表")]
        [ViewPage]
        public ActionResult SupplierList(SupplierListQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            //条件筛选
            var queryable = dbcontext.ADZ_SupplierMaster.Where(t => t.is_del == 0);
            if (!string.IsNullOrWhiteSpace(queryModel.supplier_name))
                queryable = queryable.Where(t => t.supplier_name.Contains(queryModel.supplier_name));
            if (queryModel.supplier_type != -10)
                queryable = queryable.Where(t => t.supplier_type == queryModel.supplier_type);

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var querylist = queryable.OrderByDescending(t => t.supplier_id)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<ADZ_SupplierMaster> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<ADZ_SupplierMaster>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("新增/编辑供应商")]
        [ViewPage]
        public ActionResult Add(int id = 0)
        {
            ViewBag.Title = "新增供应商";
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AddSupplierModel addSupplierModel = new AddSupplierModel();
            if (id > 0)
            {
                ViewBag.Title = "编辑供应商";
                addSupplierModel.aDZ_SupplierMaster = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == id && t.is_del == 0);
                //var details = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.supplier_id == id);
                //if (details != null)
                //    addSupplierModel.aDZ_SupplierDetails = details;
            }
            return View(addSupplierModel);
        }


        [Description("供应商支付信息")]
        [ViewPage]
        public ActionResult PayAccountList(SupplierDetailListQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //获取登录用户名
            string loginName = new CurrentUser().user.loginName;
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == managerUser.supplier_id);
                if (supplier != null)
                {
                    ViewData.Add("mg_supplier_name", supplier.supplier_name);
                    queryModel.supplier_name = supplier.supplier_name;
                }
            }

            //条件筛选
            var queryable = dbcontext.ADZ_SupplierDetails.Where(t => t.is_del == 0);
            if (!string.IsNullOrWhiteSpace(queryModel.supplier_name))
            {
                var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name.Contains(queryModel.supplier_name));
                if (supplier != null)
                    queryable = queryable.Where(t => t.supplier_id == supplier.supplier_id);
            }
            if (queryModel.audit_status != -10)
                queryable = queryable.Where(t => t.audit_status == queryModel.audit_status);

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var querylist = queryable.OrderByDescending(t => t.supplier_id)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<ADZ_SupplierDetails> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<ADZ_SupplierDetails>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("添加供应商支付信息")]
        [ViewPage]
        public ActionResult AddPayAccount()
        {
            //获取登录用户名
            string loginName = new CurrentUser().user.loginName;
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == managerUser.supplier_id);
                if (supplier != null)
                {
                    ViewData.Add("mg_supplier_id", managerUser.supplier_id);
                    ViewData.Add("mg_supplier_name", supplier.supplier_name);
                }
            }
            return View();
        }

        [Description("添加供应商支付信息")]
        [HttpPost]
        public ActionResult AddPayAccount(AddPayAccountModel model)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            if (string.IsNullOrEmpty(model.supplier_name))
            {
                resMsg.Message = "请选择供应商";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            string checkInuput = model.CheckInput();
            if (!string.IsNullOrEmpty(checkInuput))
            {
                resMsg.Message = checkInuput;
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            //通过供应商名称获取id
            var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name.Contains(model.supplier_name));
            if (supplier != null)
                model.aDZ_SupplierDetails.supplier_id = supplier.supplier_id;
            else
            {
                resMsg.Message = "供应商不存在";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            //通过银行id获取银行名称
            if (model.aDZ_SupplierDetails.bank_id > 0)
            {
                var bank = dbcontext.ADZ_Bank.FirstOrDefault(t => t.bank_id == model.aDZ_SupplierDetails.bank_id);
                if (bank != null)
                    model.aDZ_SupplierDetails.bank_name = bank.bank_name;
            }

            ADZ_SupplierDetails details = new ADZ_SupplierDetails();
            List<string> explist = new List<string>();
            explist.Add("seq_id");
            switch (model.aDZ_SupplierDetails.channel)
            {
                case 1:
                    explist.Add("alipay_account");
                    explist.Add("wechat_account");
                    break;
                case 2:
                    explist.Add("bank_id");
                    explist.Add("bank_name");
                    explist.Add("branch_bank_name");
                    explist.Add("bank_account_name");
                    explist.Add("bank_account");
                    explist.Add("wechat_account");
                    break;
                case 3:
                    explist.Add("bank_id");
                    explist.Add("bank_name");
                    explist.Add("branch_bank_name");
                    explist.Add("bank_account_name");
                    explist.Add("bank_account");
                    explist.Add("alipay_account");
                    break;
            }
            Utils.Mapper(details, model.aDZ_SupplierDetails, explist);

            dbcontext.ADZ_SupplierDetails.Add(details);
            dbcontext.SaveChanges();
            resMsg.IsSuccess = true;
            resMsg.Message = "操作成功";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("编辑供应商支付信息")]
        [ViewPage]
        public ActionResult EditPayAccount(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AddPayAccountModel model = new AddPayAccountModel();
            if (id > 0)
            {
                var details = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.seq_id == id);
                if (details != null)
                {
                    List<string> explist = new List<string>();
                    switch (model.aDZ_SupplierDetails.channel)
                    {
                        case 1:
                            explist.Add("alipay_account");
                            explist.Add("wechat_account");
                            break;
                        case 2:
                            explist.Add("bank_id");
                            explist.Add("bank_name");
                            explist.Add("branch_bank_name");
                            explist.Add("bank_account_name");
                            explist.Add("bank_account");
                            explist.Add("wechat_account");
                            break;
                        case 3:
                            explist.Add("bank_id");
                            explist.Add("bank_name");
                            explist.Add("branch_bank_name");
                            explist.Add("bank_account_name");
                            explist.Add("bank_account");
                            explist.Add("alipay_account");
                            break;
                    }
                    Utils.Mapper(model.aDZ_SupplierDetails, details, explist);

                    var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == details.supplier_id);
                    if (supplier != null)
                        model.supplier_name = supplier.supplier_name;
                }
            }
            return View(model);
        }

        [Description("编辑供应商支付信息")]
        [HttpPost]
        public ActionResult EditPayAccount(AddPayAccountModel model)
        {
            long id = model.aDZ_SupplierDetails.seq_id;
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            string checkInuput = model.CheckInput();
            if (!string.IsNullOrEmpty(checkInuput))
            {
                resMsg.Message = checkInuput;
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            //通过银行id获取银行名称
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (model.aDZ_SupplierDetails.bank_id > 0)
            {
                var bank = dbcontext.ADZ_Bank.FirstOrDefault(t => t.bank_id == model.aDZ_SupplierDetails.bank_id);
                if (bank != null)
                    model.aDZ_SupplierDetails.bank_name = bank.bank_name;
            }

            var details = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.seq_id == id);
            List<string> explist = new List<string>();
            switch (model.aDZ_SupplierDetails.channel)
            {
                case 1:
                    explist.Add("alipay_account");
                    explist.Add("wechat_account");
                    break;
                case 2:
                    explist.Add("bank_id");
                    explist.Add("bank_name");
                    explist.Add("branch_bank_name");
                    explist.Add("bank_account_name");
                    explist.Add("bank_account");
                    explist.Add("wechat_account");
                    break;
                case 3:
                    explist.Add("bank_id");
                    explist.Add("bank_name");
                    explist.Add("branch_bank_name");
                    explist.Add("bank_account_name");
                    explist.Add("bank_account");
                    explist.Add("alipay_account");
                    break;
            }
            Utils.Mapper(details, model.aDZ_SupplierDetails, explist, false);
            dbcontext.SaveChanges();
            resMsg.IsSuccess = true;
            resMsg.Message = "操作成功";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("删除支付信息")]
        [HttpPost]
        public ActionResult ToDelPayAccount(int id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.seq_id == id);
            if (entity != null)
            {
                entity.is_del = 1;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("审核通过支付信息")]
        [HttpPost]
        public ActionResult ToAudit(int id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.seq_id == id);
            if (entity != null)
            {
                entity.audit_status = (int)AuditStatus.AuditSucc;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("驳回支付信息")]
        [HttpPost]
        public ActionResult ToGiveBack(int id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.seq_id == id);
            if (entity != null)
            {
                entity.audit_status = (int)AuditStatus.AuditFail;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("新增/编辑供应商")]
        [HttpPost]
        public ActionResult Add(AddSupplierModel addSupplierModel)
        {
            long id = addSupplierModel.aDZ_SupplierMaster.supplier_id;
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            if (!addSupplierModel.aDZ_SupplierMaster.is_del.HasValue)
                addSupplierModel.aDZ_SupplierMaster.is_del = 0;

            //上传图片
            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                var file = hfc[0];
                var putResult = ImageFileBiz.UpImg(file, "company");
                if (putResult.Item1)
                    addSupplierModel.aDZ_SupplierMaster.zhizhao_url = putResult.Item3;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(addSupplierModel.aDZ_SupplierMaster.zhizhao_url))
                {
                    resMsg.Message = "请上传营业执照";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
            }


            ADZ_SupplierMaster saved_supplierMaster;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (id > 0)
            {
                var entity = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == id && t.is_del == 0);
                if (entity.supplier_name != addSupplierModel.aDZ_SupplierMaster.supplier_name)
                {
                    if (dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == addSupplierModel.aDZ_SupplierMaster.supplier_name && t.is_del == 0) != null)
                    {
                        resMsg.Message = "供应商名称已存在";
                        return Json(resMsg, JsonRequestBehavior.AllowGet);
                    }
                }
                List<string> exceptlist = new List<string>();
                exceptlist.Add("id");
                exceptlist.Add("seq_id");
                Utils.Mapper(entity, addSupplierModel.aDZ_SupplierMaster, exceptlist, false);

                dbcontext.SaveChanges();
                saved_supplierMaster = entity;

                resMsg.IsSuccess = true;
                resMsg.Message = "编辑供应商成功";
            }
            else
            {
                var user = new CurrentUser().user;
                if (user != null && user.uid > 0)
                {
                    //获取登录用户名和UID
                    addSupplierModel.aDZ_SupplierMaster.manage_name = user.loginName;
                    addSupplierModel.aDZ_SupplierMaster.manage_uid = user.uid;
                }
                else
                {
                    resMsg.Message = "登录已失效，请重新登录";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                addSupplierModel.aDZ_SupplierMaster.is_del = 0;

                if (dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == addSupplierModel.aDZ_SupplierMaster.supplier_name && t.is_del == 0) != null)
                {
                    resMsg.Message = "供应商名称已存在";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                addSupplierModel.aDZ_SupplierMaster.create_date = DateTime.Now;
                //添加供应商主表
                saved_supplierMaster = dbcontext.ADZ_SupplierMaster.Add(addSupplierModel.aDZ_SupplierMaster);
                saved_supplierMaster.status = (int)SupplierStatus.AuditSucc;
                dbcontext.SaveChanges();

                resMsg.IsSuccess = true;
                resMsg.Message = "新增供应商成功";
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }


        [Description("卖家(供应商)编辑")]
        [ViewPage]
        public ActionResult SellerEdit()
        {
            //获取登录用户名
            string loginName = new CurrentUser().user.loginName;
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                AddSupplierModel addSupplierModel = new AddSupplierModel();

                addSupplierModel.aDZ_SupplierMaster = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == managerUser.supplier_id && t.is_del == 0);
                //var details = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.supplier_id == managerUser.supplier_id);
                //if (details != null)
                //    addSupplierModel.aDZ_SupplierDetails = details;

                return View(addSupplierModel);
            }
            else
                return Redirect("/Home/Problem/");
        }

        [Description("卖家(供应商)编辑")]
        [HttpPost]
        public ActionResult SellerEdit(AddSupplierModel addSupplierModel)
        {
            long id = addSupplierModel.aDZ_SupplierMaster.supplier_id;
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            if (!addSupplierModel.aDZ_SupplierMaster.is_del.HasValue)
                addSupplierModel.aDZ_SupplierMaster.is_del = 0;

            //上传图片
            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                var file = hfc[0];
                var putResult = ImageFileBiz.UpImg(file, "company");
                if (putResult.Item1)
                    addSupplierModel.aDZ_SupplierMaster.zhizhao_url = putResult.Item3;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(addSupplierModel.aDZ_SupplierMaster.zhizhao_url))
                {
                    resMsg.Message = "请上传营业执照";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
            }


            ADZ_SupplierMaster saved_supplierMaster;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (id > 0)
            {
                var entity = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == id && t.is_del == 0);
                if (entity.supplier_name != addSupplierModel.aDZ_SupplierMaster.supplier_name)
                {
                    if (dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == addSupplierModel.aDZ_SupplierMaster.supplier_name && t.is_del == 0) != null)
                    {
                        resMsg.Message = "供应商名称已存在";
                        return Json(resMsg, JsonRequestBehavior.AllowGet);
                    }
                }

                if (entity.status == (int)SupplierStatus.AuditSucc)
                {
                    resMsg.Message = "您无权限编辑信息";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
                List<string> exceptlist = new List<string>();
                exceptlist.Add("id");
                exceptlist.Add("seq_id");
                Utils.Mapper(entity, addSupplierModel.aDZ_SupplierMaster, exceptlist, false);
                entity.status = (int)SupplierStatus.Submit;

                dbcontext.SaveChanges();
                saved_supplierMaster = entity;

                ////修改从表
                //var details = dbcontext.ADZ_SupplierDetails.FirstOrDefault(t => t.supplier_id == id);
                //if (details == null)
                //    dbcontext.ADZ_SupplierDetails.Add(addSupplierModel.aDZ_SupplierDetails);
                //else
                //    Utils.Mapper(details, addSupplierModel.aDZ_SupplierDetails, exceptlist, false);
                //dbcontext.SaveChanges();

                resMsg.IsSuccess = true;
                resMsg.Message = "信息提交成功，请等待管理员审核";
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("删除供应商")]
        [HttpPost]
        public ActionResult ToDel(int id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == id);
            if (entity != null)
            {
                entity.is_del = 1;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        #region 绑定业务员
        [Description("绑定业务员")]
        [HttpPost]
        public ActionResult BindManager(string ids, long manager_uid)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ResponseMsg resMsg = new ResponseMsg();
            if (string.IsNullOrWhiteSpace(ids))
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"传入的信息不对";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            var managerinfo = UserBiz.Instance.GetUserInfoById(manager_uid);
            if (managerinfo == null)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"负责人信息有误";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            string manager_name = managerinfo.realName;

            if (ids.EndsWith(","))
                ids = ids.Substring(0, ids.Length - 1);
            StringBuilder strb = new StringBuilder();
            string[] id_arr = Regex.Split(ids, ",");
            foreach (var item in id_arr)
            {
                long num_id = ConvertHelper.TryPraseInt(item, 0);


                if (num_id > 0)
                {
                    var obj = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_id == num_id);
                    if (obj != null)
                    {
                        obj.manage_uid = manager_uid;
                        obj.manage_name = manager_name;
                    }
                }
            }
            dbcontext.SaveChanges();

            resMsg.IsSuccess = true;
            resMsg.Message = $"处理完成";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
